package com.kcht.sylyg08.service;

import com.kcht.sylyg08.service.model.TagInfo;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Package: com.kcth.sylyg08.rest
 * @Description: ale中间件标签信息缓冲
 * @Author: lenovo
 * @CreateDate: 2019/5/14 16:00
 */
public class TagRecvBuffer {

    private static final Deque<TagInfo> tagBuffer = new LinkedList<>();

    /**
     * 向队列中添加标签信息
     */
    private static void add(TagInfo tagInfo) {
        synchronized (tagBuffer) {
            if ("RegressionTest".equals(tagInfo.getDiscoverLocation().get("IP"))) {
                System.out.println("[" + TagRecvBuffer.class + "]" + tagInfo.getEpc() + "--->JoinQueue");
            } else {
                System.out.println("[" + TagRecvBuffer.class + "]" +"向队列中加入--->"+ tagInfo.toString());
            }
            int size = 200;
            /* 长度达到200，去除第一个元素 */
            if (tagBuffer.size() == size) {
                tagBuffer.pollFirst();
            }
            tagBuffer.addLast(tagInfo);
            tagBuffer.notifyAll();
        }
    }

    /**
     * 向队列中同时添加多个标签信息
     */
    public static void add(List<TagInfo> tagInfoList) {
        for (TagInfo tagInfo : tagInfoList) {
            add(tagInfo);
        }
    }

    /**
     * 获取队列中第一个标签信息
     *
     */
    public static TagInfo fetchTag() throws InterruptedException {
        synchronized (tagBuffer) {
            TagInfo tagInfo= tagBuffer.pollFirst();
            if(tagInfo==null){
                System.out.println("[" + TagRecvBuffer.class + "]" +"队列为空，等待接收新标签");
                tagBuffer.wait();
                return fetchTag();
            }else{
                return tagInfo;
            }
        }
    }
}
